class ItemController < ApplicationController
  layout 'default', :except => :search
  
  def vote
    @item = Item.find params[:id]
    @productname = @item.name
  end
  
  def age
    return render unless params[:id]
    gifts = Gift.find :all, :conditions => ['age_id = ?', params[:id]] 
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'gift_counts desc', :conditions => ['items.id in (?)', gifts.map(&:item_id)])
    render :controller => :account, :action => :index, :template => 'account/index.rhtml'
  end
  
  def new
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'id desc')
    render :controller => :account, :action => :index, :template => 'account/index.rhtml'
  end
  
  def feed
    @pages, @items = paginate(:item, :per_page => 10, :order_by => 'id desc')
    render :controller => :account, :action => :index, :template => 'account/index.rss.rhtml', :layout => 'rss'
  end
  
  def event
    return render unless params[:id]
    gifts = Gift.find :all, :conditions => ['event_id = ?', params[:id]] 
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'gift_counts desc', :conditions => ['items.id in (?)', gifts.map(&:item_id)])
    render :controller => :account, :action => :index, :template => 'account/index.rhtml'
  end

  def gender
    return render unless params[:id]
    gifts = Gift.find :all, :conditions => ['gender = ?', params[:id]] 
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'gift_counts desc', :conditions => ['items.id in (?)', gifts.map(&:item_id)])
    render :controller => :account, :action => :index, :template => 'account/index.rhtml'
  end
  
  def view
    @item = Item.find params[:id]
    unless @item
      flash[:notice] = _("Item not found.(%{asin})") % { :asin => params[:id]}
      return redirect_to(:controller => :account, :action => :index)
    end
  end
  
  def add
    unless logged_in?
      flash[:notice] = _("You need to log in using OpenID.")
      @session[:back_url] = url_for :controller => :item, :action => :add, :path_only => false
      return redirect_to :controller => :account, :action => :login
    end
    unless request.post?
      @item = Item.new params[:item]
      return :contrlller => :item, :action => :new
    end
    type = Type.find_by_name params[:type]
    @item = Item.find :first, :conditions => ['type_id = ? and code = ?', type.id, params[:id]]
    unless @item
      case type.name
      when "rakuten"
        developer_id = RakutenWebService::DEVELOPER_ID
        url = RakutenWebService::ItemCodeSearch::URL_Builder.new developer_id
        url.itemcode = params[:id]
        rakuten  = RakutenWebService::ItemCodeSearch::Result.new url.build
        item = rakuten.item
        unless item
          flash[:notice] = _("Item is not found. Item code (%{itemcode})") % {:itemcode => params[:id]}
          return redirect_to :action => :add
        end
        @item = Item.new :name => item.itemname, :code => item.itemcode, :price => item.itemprice, :affiliateurl => item.affiliateurl, :url => item.itemurl, :smallimageurl => item.smallimageurl, :mediumimageurl => item.mediumimageurl, :reviewcount => item.reviewcount, :reviewaverage => item.reviewaverage
        @item.type = type
        @item.name = params[:productname]
        developer_id = RakutenWebService::DEVELOPER_ID
        url = RakutenWebService::GenreSearch::URL_Builder.new developer_id
        url.genreid = item.genreid
        rakuten = RakutenWebService::GenreSearch::Result.new url.build
        @item.genre = Genre.find_by_name rakuten.genres['current'].genrename
        unless @item.genre
          @item.genre = Genre.create :name => rakuten.genres['current'].genrename
        end
        @item.gift_counts = 0
        @item.save
      when "amazon"
        item = Amazon::Ecs.item_lookup(params[:id], :response_group => 'Large').items[0]
        @item = Item.new :name => item.get("title"), :code => item.get("asin"), :price => item.get("listprice/amount"), :affiliateurl => item.get("detailpageurl"), :url => item.get("detailpageurl"), :smallimageurl => item.get("smallimage/url"), :mediumimageurl => item.get("mediumimage.url"), :reviewcount => item.get("customerreviews/totalreviews"), :reviewaverage => item.get("customerreviews/averagerating")
        @item.type = type
        @item.name = params[:productname]
        @item.genre = Genre.find_by_name item.get("itemattributes/productgroup")
        unless @item.genre
          @item.genre = Genre.create :name => item.get("itemattributes/productgroup")
        end
        @item.gift_counts = 0
        @item.save
      end
    end
    # Add new gift
    gift = Gift.new params[:gift]
    gift.item = @item
    gift.user_id = @session[:user_id]
    gift.save
    @item.update_attribute :gift_counts, @item.gift_counts+1
    flash[:notice] = _("Your gift saved.")
    redirect_to :controller => :account, :action => :index
  end

  def detail
    @search_type = params[:type]
    @gift = Gift.new
    @itemcode = params[:id]
    case params[:type]
    when "rakuten"
      developer_id = RakutenWebService::DEVELOPER_ID
      url = RakutenWebService::ItemCodeSearch::URL_Builder.new developer_id
      url.itemcode = params[:id]
      rakuten  = RakutenWebService::ItemCodeSearch::Result.new url.build
      @item = rakuten.item
      unless @item
        flash[:notice] = _("Item is not found. Item code (%{itemcode})") % {:itemcode => params[:id]}
        return redirect_to :action => :add
      end
      @productname = @item.itemname
    when "amazon"
      @item = Amazon::Ecs.item_lookup(params[:id], :response_group => 'Large').items[0]
      unless @item
        flash[:notice] = _("Item is not found. ASIN (%{asin})") % {:asin => params[:id]}
        return redirect_to :action => :add
      end
      @productname = @item.get("title")
      # @item = Item.new(:name => item.get("title"), :code => item.get("asin"), :price => item.get("listprice/amount"))
    end
  end
  
  def site
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'gift_counts desc', :conditions => ['items.name like ?', "%#{params[:search]}%"])
    @term = params[:search]
    flash[:notice] = _('Search result "%{term}"') % { :term => @term}
    render :controller => :account, :action => :index, :template => 'account/index.rhtml'
  end
  
  def tag
    return render unless params[:id]
    gifts = Gift.find_tagged_with(params[:id])
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'gift_counts desc', :conditions => ['items.id in (?)', gifts.map(&:item_id)])
    render :controller => :account, :action => :index, :template => 'account/index.rhtml'
  end
  
  def search
    @header = nil
    @items = nil
    @keyword = params[:keyword]
    @search_type = params[:search_type]
    case params[:search_type]
    when 'rakuten'
      params[:page] = params[:page] || 1
      developer_id = RakutenWebService::DEVELOPER_ID
      url = RakutenWebService::ItemSearch::URL_Builder.new developer_id
      url.keyword = params[:keyword]
      url.page = params[:page]
      url.hits = 10
      rakuten  = RakutenWebService::ItemSearch::Result.new url.build
      count = rakuten.header.count.to_i
      logger.debug "Count::#{rakuten.header.count}"
      per_page = 10
      @pages = Paginator.new(self, count, per_page, params[:page])
      @header = rakuten.header
      @items = rakuten.items
    when 'amazon'
      params[:page] = params[:page] || 1
      res = Amazon::Ecs.item_search(params[:keyword], :response_group => 'Large', :search_index => 'Blended', :ItemPage => params[:page])
      count = res.total_results
      per_page = 10
      @pages = Paginator.new(self, count, per_page, params[:page])
      @header = res
      @items  = res.items
    end
  end
end
